<template>
    <el-dialog v-model="show" :close-on-click-modal="false" width="35%" @close="closeCallback()">
        <template #header>
            <span>{{ title }}</span>
        </template>
        <template #default>
            <el-form ref="formRef" :rules="rules" :model="form" label-width="auto">
                <el-form-item label="姓名" prop="username">
                    <el-input
                        maxlength="20"
                        v-model.trim="form.username"
                        show-word-limit
                        placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input maxlength="11" v-model.trim="form.mobile" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roleIdList">
                    <el-select v-model="form.roleIdList" multiple placeholder="请选择角色">
                        <el-option
                            v-for="item in roles"
                            :key="item.roleId"
                            :label="item.roleName"
                            :value="item.roleId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="form.status" placeholder="请选择状态">
                        <el-option
                            v-for="item in status"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button plain @click="closeHandler">取消</el-button>
                <el-button type="primary" @click="submitHandler">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed, reactive, inject, onMounted } from 'vue';
import constants from '@/commons/constants';
import request from '@/request';
import { packSelectObjUtil, isMobile, cloneDeep } from '@/commons/utils';
import { isNotEmpty } from '../../../../commons/utils';
import { ElMessage } from 'element-plus';

/** 通信bus */
const bus = inject('bus');

/** 弹框显示隐藏 */
const props = defineProps({
    modelValue: Boolean
});
const emit = defineEmits(['update:modelValue']);
const show = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

/** form表单 */
const fzForm = {
    userId: '',
    username: '',
    mobile: '',
    roleIdList: [],
    status: 1
};
const formRef = ref(null);
const form = reactive(cloneDeep(fzForm));
const row = reactive({});
bus.on('user:edit', row => {
    if (row.hasOwnProperty('userId')) {
        Object.assign(form, row);
        form.roleIdList.length = 0;
        row.roleList.map(v => {
            form.roleIdList.push(v.roleId);
        });
        delete form.roleList;
    } else {
        Object.assign(form, cloneDeep(fzForm));
    }
});
const title = computed(() => {
    return isNotEmpty(form.userId) ? '编辑账号' : '新建账号';
});

/** 查询所有角色 */
const roles = reactive([]);
const quertRoleAllHandler = async () => {
    const res = await request('quertRoleListServ', { pageNum: 1, pageSize: 9999 });
    const { list } = res.data;
    roles.push(...list);
};

/** 状态集合 */
const status = reactive(packSelectObjUtil(constants.IS_ENABLED));

/**
 * 手机号验证
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 */
const validatePhone = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入手机号'));
    } else if (isMobile(value)) {
        callback();
    } else {
        callback(new Error('请输入正确的手机号!'));
    }
};

/**
 * 表单验证
 */
const rules = reactive({
    username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validatePhone, trigger: 'blur' }
    ],
    roleIdList: [{ required: true, message: '请选择角色', trigger: 'blur' }]
});

/**
 * 关闭drawer
 */
const closeHandler = () => {
    show.value = false;
};
const submitHandler = () => {
    formRef.value.validate(async valid => {
        if (valid) {
            const apiName = isNotEmpty(form.userId) ? 'updateAccountServ' : 'addAccountSrev';
            await request(apiName, form);
            ElMessage.success('操作成功');
            closeHandler();
            bus.emit('user:query');
        }
    });
};
const closeCallback = () => {
    formRef.value.resetFields();
};

onMounted(() => {
    quertRoleAllHandler();
});
</script>
